var date;
var deviceId;
let currentPrice = Number(0);
$(function () {
    date = getCurrentDate(1);
    chart_bar1.setOption(option_bar1);
    chart_line1.setOption(option_line1);
    chart_bar2.setOption(option_bar2);
    chart_radar.setOption(option_radar);
    chart_line2.setOption(option_line2);
    chart_pictorialBar1.setOption(option_pictorialBar1);
    modalChart_time.setOption(option_bar1);
    modalChart_usage.setOption(option_line1);
    modalChart_electric.setOption(option_bar2);
    modalChart_electric.setOption({
        grid: {
            left: 20,
            right: 35
        },
        series: [{
            itemStyle: {
                normal: {
                    //不同时段柱子设置不同颜色
                    color: function (params) {
                        let colorList = [
                            "#009AEA",//谷 0-8
                            "#F2CB6B",//平 12-17，21-24
                            "#FF8B35"//峰 8-12，17-21
                        ];
                        if (Number(params.name.substr(6, 2)) >= 0 && Number(params.name.substr(6, 2)) < 8) {//谷
                            return colorList[0];
                        } else if ((Number(params.name.substr(6, 2)) >= 12 && Number(params.name.substr(6, 2)) < 17) || (Number(params.name.substr(6, 2)) >= 21)) {
                            return colorList[1];
                        } else {
                            return colorList[2]
                        }
                    }
                }
            }
        }]
    });
    modalChart_power.setOption(option_line2);
    modalChart_power.setOption({
        grid: {
            left: 20,
            right: 35
        }
    });
    modalChart_analysis.setOption(option_bar3);
    // console.log(sessionStorage.getItem("deviceID"));
    if (sessionStorage.getItem("deviceID")) {
        loadDeviceDataByDeviceId();
    } else {
        loadDefaultDevice();
    }
    loadTree();

});

/* 切换展示基本信息、用电分析 */
function showSection(e, num) {
    $(e).parent().siblings().children().removeClass('active');
    $(e).addClass('active');
    $('.device-section').addClass('d-none');
    $('#device_section_' + num).removeClass('d-none');
    chart_bar2.resize();
    chartNoDataHintResize($('#chart_bar2'));
    chart_radar.resize();
    chart_line2.resize();
    chartNoDataHintResize($('#chart_line2'));
    chart_pictorialBar1.resize();
    /*生产时长*/
    chart_bar1.resize();
    chartNoDataHintResize($('#chart_bar1'));
    /*设备使用率*/
    chart_line1.resize();
    chartNoDataHintResize($('#chart_line1'));

}

/* 更多 */
function viewMore(para) {
    let beginTime;
    let endTime;
    chartNoDataHintHide($('#viewMoreModal_' + para));
    $('#viewMoreModal_' + para).modal();
    if (para == 'time') {
        $('#searchTimeBegin_time').val("");
        $('#searchTimeEnd_time').val("");
        //处理生产时长更多图表
        beginTime = $('#searchTimeBegin_time').val();
        endTime = $('#searchTimeEnd_time').val();
        //  获取生产时长
        loadProductionTimeData(beginTime, endTime);
    } else if (para == 'usage') {
        //  处理设备使用率图表
        $('#searchTimeBegin_usage').val("");
        $('#searchTimeEnd_usage').val("");
        beginTime = $('#searchTimeBegin_usage').val();
        endTime = $('#searchTimeEnd_usage').val();
        loadEquipmentUsage(beginTime, endTime);
    } else if (para == 'electric') {
        $('#searchTimeBegin_electric').val("");
        $('#searchTimeEnd_electric').val("");
        //  处理用电量图表
        beginTime = $('#searchTimeBegin_electric').val();
        endTime = $('#searchTimeEnd_electric').val();
        loadTodayElectricityData(beginTime, endTime);
    } else if (para == 'power') {
        $('#searchTimeBegin_power').val("");
        $('#searchTimeEnd_power').val("");
        //  处理功率图表
        beginTime = $('#searchTimeBegin_power').val();
        endTime = $('#searchTimeEnd_power').val();
        loadRealPowerData(beginTime, endTime);
    } else if (para == 'analysis') {
        $('#searchTimeBegin_analysis').val("");
        $('#searchTimeEnd_analysis').val("");
        //  处理用电分析图表
        beginTime = $('#searchTimeBegin_analysis').val();
        endTime = $('#searchTimeEnd_analysis').val();
        loadElectricityAnalysisData(beginTime, endTime);
    }

    $('#viewMoreModal_' + para).on('shown.bs.modal', function (e) {
        eval('modalChart_' + para).resize();
        chartNoDataHintResize($('#modalChart_' + para));
    })
}

//模拟电量功率的x轴数据
function increaseArr2(count, begin) {//count长度,begin起始值
    var data = [];
    for (var i = 0; i < count; i++) {
        var h = i + begin < 10 ? '0' + (i + begin) : i + begin;
        data[i] = '2020-01-01 ' + h + ':00';
    }
    return data;
}

function loadDeviceDataByDeviceId() {
    var id = sessionStorage.getItem("deviceID");
    if (id) {
        deviceId = id;
        getJson("/device/getProduceDeviceById", {id: id}, 'GET', function (result) {
            if (result.status == 200) {
                let data = result.data;
                VOData(data);
            } else {
                myAlert("提示", "加载设备数据失败");
            }
        })
    }
}

function loadDefaultDevice() {
    getJson("/device/getProduceDefaultDevice", null, 'GET', function (data) {
        if (data['code'] == 200) {
            let device = data['payload']['data'];
            deviceId = device['id'];
            VOData(device);
        } else {
            myAlert('提示', '当前用户归属企业无设备');
        }
    })
}

function loadTree() {
    showImpLoading(LOADING);
    layui.use('tree', function () {
        getJson('/device/getProductionDeviceList', {"param": $('#pram_id').val()}, 'GET', function (data) {
            hideLoading();
            if (data['code'] == 200) {
                var tree = layui.tree;
                //渲染
                var inst1 = tree.render({
                    elem: '#deviceListTree',
                    //showCheckbox: true,//是否显示复选框
                    data: buildTree(data['payload']['data']),
                    click: function (obj) {
                        if (obj.data.id) {
                            deviceId = obj.data.id;
                            /*根据ID查询信息*/
                            getJson("/device/getProduceDeviceById", {"id": obj.data.id}, 'GET', function (result) {
                                if (result.status == 200) {
                                    let data = result.data;
                                    VOData(data);
                                } else {
                                    myAlert("提示", "加载设备数据失败");
                                }
                            })
                        }
                    }
                })
            } else {
                alert(data['message'])
            }
        })
    });
}

/*渲染数据*/
function VOData(data) {
    let time = current().substring(10, 14);
    /*今日电量*/
    chartNoDataHintHide($('#chart_bar2'));
    /*实时功率*/
    chartNoDataHintHide($('#chart_line2'));
    /*生产时长*/
    chartNoDataHintHide($('#chart_bar1'));
    /*设备使用率*/
    chartNoDataHintHide($('#chart_line1'));
    showLoading(LOADING)
    $('#deviceName-id').html(data.name);
    $('#device-id').html(data.name);
    $('#deviceSn-id').html('编号:' + data.sn);
    $('#zh_id').html('站号:' + data.port);
    $('#image-id').attr('src', fileUrl + data.image);
    if (judgeThePeakValleyFlat(time) == 'max') {
        currentPrice = data.maxPrice;
    } else if (judgeThePeakValleyFlat(time) == 'min') {
        currentPrice = data.minPrice;
    } else {
        currentPrice = data.avgPrice;
    }
    let i;
    switch (data.status) {
        case 1:
            i = '<i class="iconfont icon-gongzuo mr-1 text-powerOn"></i>' + '运行中';
            break;
        case 2:
            i = '<i class="iconfont icon-gongzuo mr-1 text-standby"></i>' + '空闲';
            break;
        case 3:
            i = '<i class="iconfont icon-gongzuo mr-1 text-powerOff"></i>' + '离线';
            break;
        case 4:
            i = '<i class="iconfont icon-gongzuo mr-1 text-fault"></i>' + '报警';
            break;
    }
    $('#status-div').empty();
    $('#status-div').append(i);
    getJson("/sys/org/info", {id: data['enterpise']}, 'GET', function (org) {
        $('#provinceName').text(org['payload']['data']['province']);
        $('#cityName').text(org['payload']['data']['city']);
        $('#enterpriseName').text(org['payload']['data']['name']);
    });
    //  查询当前设备关联的采集设备
    getJson("/device/getDeviceByGroup", {"group": data.group}, 'GET', function (result) {
        if (result.length != 0) {
            $('#cj_name').html(result.name);
            $('#cj_bh').html(result.sn);
            let iLabel;
            switch (result.status) {
                case 1:
                    iLabel = '<i class="iconfont icon-gongzuo mr-1 text-powerOn"></i>' + '运行中';
                    break;
                case 2:
                    iLabel = '<i class="iconfont icon-gongzuo mr-1 text-standby"></i>' + '空闲';
                    break;
                case 3:
                    iLabel = '<i class="iconfont icon-gongzuo mr-1 text-powerOff"></i>' + '离线';
                    break;
                case 4:
                    iLabel = '<i class="iconfont icon-gongzuo mr-1 text-fault"></i>' + '报警';
                    break;
                default:
                    iLabel = '<i class="iconfont icon-gongzuo mr-1 text-standby"></i>' + '空闲';
                    break;
            }
            $('#cj_status').empty();
            $('#cj_status').append(iLabel);
        } else {
            $('#cj_name').html("");
            $('#cj_bh').html("");
        }


    })
    /*查询关联生产设备的维保情况*/
    getJson("/maintenance/getMaintenanceInfoByDId", {"id": data.id}, 'GET', function (result) {
        if (result.date) {
            $('#day_id').html(result.str);
            $('#time_id').html(result.date.substring(0, 10));
        }
    })
    //  用电分析
    getJson("/device/getElectricityAnalysisData", {id: data.id}, 'GET', function (result) {
        $('#jkzs_fs').html(Math.round(Number(result.health / 100) * 100));
        let newArray = new Array();
        newArray.push(Math.round(Number(result.voltageDeviation / 100) * 100));
        newArray.push(Math.round(Number(result.frequencyDeviation / 100) * 100));
        if(data.powerSupply != 1){
            newArray.push(Math.round(Number(result.unblance / 100) * 100));
        }
        newArray.push(Math.round(Number(result.loadRate / 100) * 100));
        newArray.push(Math.round(Number(result.powerFactor / 100) * 100));
        $('#glys_id').html(Math.round(Number(result.powerFactor / 100) * 100) / 100);
        $('#fzl_id').html(result.loadRate);
        if (newArray.length != 0) {
            if(data.powerSupply == 1){
                chart_radar.setOption({
                    title: {
                        text: '单相电接入设备无三相不平衡数据'
                    },
                    radar: {
                        center: ['50%', '45%'],
                        radius: '70%',
                        indicator: [
                            {name: '电压偏差', max: 100},
                            {name: '频率偏差', max: 100},
                            {name: '负载率', max: 100},
                            {name: '功率因数', max: 100}
                        ]
                    },
                    series: [{
                        data: [{
                            value: newArray
                        }]
                    }]
                });
            } else{
                chart_radar.setOption({
                    title: {
                        text: ''
                    },
                    radar: {
                        center: ['50%', '50%'],
                        radius: '80%',
                        indicator: [
                            {name: '电压偏差', max: 100},
                            {name: '频率偏差', max: 100},
                            {name: '三相不平衡', max: 100},
                            {name: '负载率', max: 100},
                            {name: '功率因数', max: 100}
                        ]
                    },
                    series: [{
                        data: [{
                            value: newArray
                        }]
                    }]
                });
            }
        }

        if (result.createTime) {
            $('#dataTime_id').html(result.createTime.substring(10));
        } else {
            $('#dataTime_id').html('');
        }

        if (result.positionDeviation == 1) {
            $('#offset_id').empty();
            $('#offset_id').append('<div class="font-p16 font-weight-bold" >位置偏移</div> <svg t="1592207529861" class="icon" viewBox="0 0 1732 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5180" width="44" height="26"><path d="M346.584615 187.076923h1039.753847c191.409231 0 346.584615 145.447385 346.584615 324.923077s-155.175385 324.923077-346.584615 324.923077H346.584615C155.175385 836.923077 0 691.475692 0 512s155.175385-324.923077 346.584615-324.923077z" fill="#CAE3FF" p-id="5181"></path><path d="M727.394462 512c0 277.661538 225.083077 502.784 502.784 502.784C1507.84 1014.784 1732.923077 789.661538 1732.923077 512S1507.84 9.255385 1230.178462 9.255385C952.516923 9.255385 727.394462 234.338462 727.394462 512z" fill="#2185F5" p-id="5182"></path></svg>');
            $('#status_id').html('开启');
        } else {
            $('#offset_id').empty();
            $('#offset_id').append('<div class="font-p16 font-weight-bold" >位置偏移</div> <svg t="1598434215978" class="icon" viewBox="0 0 1764 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="29056" width="44" height="26"><path d="M352.951571 181.08849h1058.84962c194.925075 0 352.951571 148.118779 352.951571 330.891652s-158.025477 330.891652-352.951571 330.891652H352.951571C158.025477 842.871794 0 694.753015 0 511.980142s158.025477-330.891652 352.951571-330.891652z" fill="#7C89A6" p-id="29057"></path><path d="M0 511.980142c0 282.762494 229.217648 512.019858 512.019858 512.019858 282.762494 0 511.977087-229.257364 511.977087-512.019858S794.782352 0 512.021895 0 0 229.217648 0 511.980142z" fill="#D9DFE9" p-id="29058"></path></svg>');
            $('#status_id').html('关闭');
        }
    })
    //  查询当前设备今日用电量
    getJson("/device/getTodayElectricity", {id: data.id}, 'GET', function (result) {
        if (result.length == 0) {
            $('#ljdl_id').text("0kWh");
            chart_bar2.setOption({
                xAxis: {
                    data: []
                },
                series: [{
                    data: []
                }]
            });
            chartNoDataHint($('#chart_bar2'));
        } else {
            let xArray = new Array();
            let yArray = new Array();
            let ljdl = 0;
            for (let j = 0; j < result.length; j++) {
                xArray.push(result[j].date.substr(11, 5));
                yArray.push(result[j].str);
                ljdl += Number(result[j].str);
            }
            $('#ljdl_id').text(Math.round(ljdl * 100) / 100 + "kWh");
            let option_bar2 = {//今日用电量柱状图
                xAxis: {
                    data: xArray
                },
                series: [{
                    data: yArray
                }]
            };
            chart_bar2.setOption(option_bar2);
        }
    })
    //  获取实时功率
    getJson("/device/getRealPower", {id: data.id}, 'GET', function (result) {
        if (result.length == 0) {
            chart_line2.setOption({
                xAxis: {
                    data: []
                },
                series: [{
                    data: []
                }]
            });
            chartNoDataHint($('#chart_line2'));
        } else {
            let xArray = new Array();
            let yArray = new Array();
            for (let j = 0; j < result.length; j++) {
                xArray.push(result[j].date.substr(11, 5));
                yArray.push(result[j].str);
            }
            let option_line2 = {//实时功率折线图
                xAxis: {
                    data: xArray
                },
                series: [{
                    data: yArray
                }]
            };
            chart_line2.setOption(option_line2);
        }
    })
    //  获取生产时长
    getJson("/device/getProductionTime", {"id": data.id, "type": 0}, 'GET', function (result) {
            if (result.length == 0) {
                chart_bar1.setOption({//生产时长柱状图
                    xAxis: {
                        data: []
                    },
                    series: [{
                        data: []
                    }]
                });
                $('#scsc_id').html('0h');
                chartNoDataHint($('#chart_bar1'));
            } else {
                let xArray = new Array();
                let yArray = new Array();
                for (let j = 0; j < result.length; j++) {
                    if (result[j].date.substring(0, 10) == date) {
                        $('#scsc_id').html(Math.round(result[j].str * 100) / 100 + 'h');
                    }
                    xArray.push(result[j].date.substring(5, 10));
                    yArray.push(Math.round(result[j].str * 100) / 100);
                }
                chart_bar1.setOption({//生产时长柱状图
                    xAxis: {
                        data: xArray
                    },
                    series: [{
                        data: yArray
                    }]
                });
            }
        }
    )
    //  获取设备使用率
    getJson("/device/getDeviceUserate", {"id": data.id, "type": 2}, 'GET', function (result) {
            if (result.length == 0) {
                chart_line1.setOption({//生产时长柱状图
                    xAxis: {
                        data: []
                    },
                    series: [{
                        data: []
                    }]
                });
                chartNoDataHint($('#chart_line1'));
                $('#syl_id').html("0%");
                $('#syl_id').width("0%");
            } else {
                let xArray = new Array();
                let yArray = new Array();
                var sum = 0;
                for (let j = 0; j < result.length; j++) {
                    xArray.push(result[j].createTime);
                    yArray.push(Math.round(result[j].usageRate * 100) / 100);
                    sum += Number(result[j].usageRate);
                }
                let avg = Number(sum / 7);
                $('#syl_id').html(Math.round(avg * 100) / 100 + "%");
                $('#syl_id').width(sum / 7 + "%");
                let option_line1 = {//设备使用率折线图
                    xAxis: {
                        data: xArray
                    },
                    series: [{
                        data: yArray
                    }]
                };
                chart_line1.setOption(option_line1);
            }
        }
    )
    // loadElectricityPriceData();
    loadPowerConsumptionStatistics();

}

/*更多生产时长图表*/
function loadProductionTimeData(beginTime, endTime) {
    showLoading(LOADING)
    getJson("/device/getProductionTime", {
        "id": deviceId,
        "beginTime": beginTime,
        "endTime": endTime,
        "type": 1
    }, 'GET', function (result) {
        chartNoDataHintHide($('#modalChart_time'));
        if (result.length == 0) {
            chartNoDataHint($('#modalChart_time'));
            hideLoading();
            return;
        }
        let xArray = new Array();
        let yArray = new Array();

        for (let j = 0; j < result.length; j++) {
            xArray.push(result[j].date.substring(5, 10));
            yArray.push(result[j].str);
        }
        let option_bar1 = {//生产时长柱状图
            xAxis: {
                data: xArray
            },
            series: [{
                data: yArray
            }]
        };
        modalChart_time.setOption(option_bar1);
        hideLoading();
    })
}

//更多用电量图表
function loadTodayElectricityData(beginTime, endTime) {
    chartNoDataHintHide($('#modalChart_electric'));
    if (oneMonthLimit(beginTime, endTime)) {
        showModalHint("none", "请将时间范围控制在30天内");
        return;
    }
    showLoading(LOADING)
//  根据条件查询用电量
    getJson("/device/getTodayElectricityByParam", {
            "id": deviceId,
            "beginTime": beginTime,
            "endTime": endTime
        }, 'GET', function (result) {
            if (result.length == 0) {
                $('#ljdlgd_id').text('0kWh');
                $('#ygdf_id').text('0万元');
                chartNoDataHint($('#modalChart_electric'));
                hideLoading();
                return;
            }
            getJson("/device/getDeviceByDid", {id: deviceId}, 'GET', function (device) {
                let xArray = new Array();
                let yArray = new Array();
                let maxCount = 0;
                let minCount = 0;
                let avgCount = 0;
                for (let j = 0; j < result.length; j++) {
                    switch (judgeThePeakValleyFlat(result[j].date.substr(11, 5))) {
                        case 'min':
                            minCount += Number(result[j].str);
                            break;
                        case 'avg':
                            avgCount += Number(result[j].str);
                            break;
                        case 'max':
                            maxCount += Number(result[j].str);
                            break;
                    }
                    xArray.push(result[j].date.substr(5, 11));
                    yArray.push(result[j].str);
                }
                let count = maxCount * device['maxPrice'] + minCount * device['minPrice'] + avgCount * device['avgPrice'];
                $('#ljdlgd_id').text(Math.round((maxCount + minCount + avgCount) * 100) / 100 + 'kWh');
                $('#ygdf_id').text(Math.round(count) / 10000 + '万元');
                modalChart_electric.setOption({//今日用电量柱状图
                    xAxis: {
                        data: xArray
                    },
                    series: [{
                        data: yArray
                    }]
                });
                hideLoading();
            })
        }
    )
}

function loadRealPowerData(beginTime, endTime) {
    chartNoDataHintHide($('#modalChart_power'));
    if (oneMonthLimit(beginTime, endTime)) {
        showModalHint("none", "请将时间范围控制在30天内");
        return;
    }
    showLoading(LOADING);
    //  获取更多功率
    getJson("/device/getRealPowerParam", {
            "id": deviceId,
            "beginTime": beginTime,
            "endTime": endTime
        }, 'GET', function (result) {
            chartNoDataHintHide($('#modalChart_power'));
            if (result.length == 0) {
                chartNoDataHint($('#modalChart_power'));
                hideLoading();
                return;
            }
            let xArray = new Array();
            let yArray = new Array();
            for (let j = 0; j < result.length; j++) {
                xArray.push(result[j].date.substr(5, 11));
                yArray.push(result[j].str);
            }
            modalChart_power.setOption({//实时功率折线图
                xAxis: {
                    data: xArray
                },
                series: [{
                    data: yArray
                }]
            });
            hideLoading();
        }
    )
}

/*加载更多设备使用率*/
function loadEquipmentUsage(beginTime, endTime) {
    showLoading(LOADING)
    //  获取设备使用率
    getJson("/device/getDeviceUserate", {
        "id": deviceId,
        "beginTime": beginTime,
        "endTime": endTime,
        "type": 1
    }, 'GET', function (result) {
        chartNoDataHintHide($('#modalChart_usage'));
        if (result.length == 0) {
            chartNoDataHint($('#modalChart_usage'));
            hideLoading();
            return;
        }
        let xArray = new Array();
        let yArray = new Array();
        for (let j = 0; j < result.length; j++) {
            xArray.push(result[j].createTime);
            yArray.push(Math.round(result[j].usageRate * 100) / 100);
        }
        // console.log(xArray);
        // console.log(yArray);
        modalChart_usage.setOption(option_line1 = {//设备使用率折线图
            xAxis: {
                data: xArray
            },
            series: [{
                data: yArray
            }]
        });
        hideLoading();
    })
}

function loadElectricityAnalysisData(beginTime, endTime) {
    if (oneMonthLimit(beginTime, endTime)) {
        showModalHint("none", "请将时间范围控制在30天内");
        return;
    }
    showLoading(LOADING);
    getJson("/device/getElectricityAnalysisDataByParam", {
        "id": deviceId,
        "beginTime": beginTime,
        "endTime": endTime
    }, 'GET', function (result) {
        chartNoDataHintHide($('#modalChart_analysis'));
        if (result.length == 0) {
            chartNoDataHint($('#modalChart_analysis'));
            hideLoading();
            return;
        }
        //电压偏差
        let voltageDeviationArray = new Array();
        //频率偏差
        let frequencyDeviationArray = new Array();
        //三相不平衡
        let unblanceArray = new Array();
        //负载率
        let loadRateArray = new Array();
        //健康指数
        let healthArray = new Array();
        //功率因数
        let powerFactor = new Array();
        //X轴时间
        let timeArray = new Array();
        for (let i = 0; i < result.length; i++) {
            voltageDeviationArray.push(result[i].voltageDeviation);
            frequencyDeviationArray.push(result[i].frequencyDeviation);
            unblanceArray.push(result[i].unblance);
            loadRateArray.push(result[i].loadRate);
            healthArray.push(result[i].health);
            powerFactor.push(result[i].powerFactor);
            timeArray.push(result[i].createTime);
        }
        modalChart_analysis.setOption({//用电分析柱状/折线图
            dataZoom: [{
                startValue: timeArray.length - 7,
                endValue: timeArray.length - 1,
            }],
            xAxis: {
                data: timeArray
            },
            series: [{
                data: voltageDeviationArray
            }, {
                data: powerFactor
            }, {
                data: frequencyDeviationArray
            }, {
                data: unblanceArray
            }, {
                data: loadRateArray
            }, {
                data: healthArray
            }]
        });
        hideLoading();
    })
}

function loadPowerConsumptionStatistics() {
    getJson("/device/getPowerConsumptionStatistics", {"id": deviceId}, 'GET', function (result) {
        $("#thisMonth_id").html(Math.round(result.ebtm) / 10000);
        $("#today_id").html(Math.round(result.electricityCharge) / 10000);
        $("#yesterday_id").html(Math.round(result.yeb) / 10000);
        $('#ssyg_id').html(result.realActive);
        $('#sswg_id').html(result.realReactive);
        chart_pictorialBar1.setOption({
            series: [{
                data: [{
                    value: currentPrice,//当前电价
                    itemStyle: {
                        color: '#5B8FF9'
                    }
                }, {
                    value: result.dailyPrice,//昨日电价
                    itemStyle: {
                        color: '#82D0EF'
                    }
                }, {
                    value: result.eplm,//上月电价
                    itemStyle: {
                        color: '#F6BD16'
                    }
                }]
            }]
        });
        hideLoading();
    })
}

function buildTree2(parent, data) {
    let tree = [];
    for (let item of data) {
        let node = getNode(parent, 'title', item['enterprise']['province']);
        if (node == null) {
            node = {};
            node['title'] = item['enterprise']['province'];
            node['spread'] = true;
            node['children'] = [];
            tree.push(node);
        }
    }
}

function buildTree(data) {
    let tree = [];
    for (let item of data) {
        let province = getNode(tree, 'title', item['enterprise']['province']);
        if (province == null) {
            province = {};
            province['title'] = item['enterprise']['province'];
            province['spread'] = true;
            province['children'] = [];
            tree.push(province);
        }
        let city = getNode(province['children'], 'title', item['enterprise']['city']);
        if (city == null) {
            city = {};
            city['title'] = item['enterprise']['city'];
            city['spread'] = true;
            city['children'] = [];
            province['children'].push(city);
        }
        let enterprise = getNode(city['children'], 'title', item['enterprise']['name']);
        if (enterprise == null) {
            enterprise = {};
            enterprise['title'] = item['enterprise']['name'];
            enterprise['spread'] = true;
            enterprise['children'] = [];
            city['children'].push(enterprise);
        }
        let device = getNode(enterprise['children'], 'id', item['id']);
        if (device == null) {
            device = {};
            switch (item['status']) {
                case 1:
                    device['title'] = "<i class='iconfont icon-gongzuo text-powerOn mr-1'></i>" + item['name'];
                    break;
                case 2:
                    device['title'] = "<i class='iconfont icon-gongzuo text-standby mr-1'></i>" + item['name'];
                    break;
                case 3:
                    device['title'] = "<i class='iconfont icon-gongzuo text-powerOff mr-1'></i>" + item['name'];
                    break;
                case 4:
                    device['title'] = "<i class='iconfont icon-gongzuo text-fault mr-1'></i>" + item['name'];
                    break;
            }
            device['id'] = item['id'];
            device['spread'] = true;
            enterprise['children'].push(device);
        }
    }
    return tree;
}

function getNode(set, key, value) {
    for (let item of set) {
        if (item[key] == value) {
            return item;
        }
    }
    return null;
}

laydate.render({
    elem: '#searchTimeBegin_time',
    max: 0 //最小值今天
});
laydate.render({
    elem: '#searchTimeEnd_time'
    , max: 0
});
laydate.render({
    elem: '#searchTimeBegin_usage',
    max: -1
});
laydate.render({
    elem: '#searchTimeEnd_usage',
    max: -1
});
laydate.render({
    elem: '#searchTimeBegin_electric',
    type: 'datetime',
    max: getCurrentDate(1) + ' 23:59:59' //最大值今天最后一秒
});
laydate.render({
    elem: '#searchTimeEnd_electric',
    type: 'datetime',
    max: getCurrentDate(1) + ' 23:59:59' //最大值今天最后一秒
});
laydate.render({
    elem: '#searchTimeBegin_power',
    type: 'datetime',
    max: getCurrentDate(1) + ' 23:59:59' //最大值今天最后一秒
});
laydate.render({
    elem: '#searchTimeEnd_power',
    type: 'datetime',
    max: getCurrentDate(1) + ' 23:59:59' //最大值今天最后一秒
});
laydate.render({
    elem: '#searchTimeBegin_analysis',
    type: 'datetime',
    max: getCurrentDate(1) + ' 23:59:59' //最大值今天最后一秒
});
laydate.render({
    elem: '#searchTimeEnd_analysis',
    type: 'datetime',
    max: getCurrentDate(1) + ' 23:59:59' //最大值今天最后一秒
});


var chart_bar1 = echarts.init(document.getElementById('chart_bar1'));
var chart_line1 = echarts.init(document.getElementById('chart_line1'));
var chart_bar2 = echarts.init(document.getElementById('chart_bar2'));
var chart_radar = echarts.init(document.getElementById('chart_radar'));
var chart_line2 = echarts.init(document.getElementById('chart_line2'));
var chart_pictorialBar1 = echarts.init(document.getElementById('chart_pictorialBar1'));
var modalChart_time = echarts.init(document.getElementById('modalChart_time'));//modal图表-生产时长
var modalChart_usage = echarts.init(document.getElementById('modalChart_usage'));//modal图表-设备使用率
var modalChart_electric = echarts.init(document.getElementById('modalChart_electric'));//modal图表-用电量
var modalChart_power = echarts.init(document.getElementById('modalChart_power'));//modal图表-实时功率
var modalChart_analysis = echarts.init(document.getElementById('modalChart_analysis'));//modal图表-用电分析

var option_bar1 = {//生产时长柱状图
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    grid: {
        top: 10,
        left: 0,
        right: 0,
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        type: 'category',
        // data: ['6-1', '6-2', '6-3', '6-4', '6-5', '6-6', '6-7'],
        axisLine: {
            lineStyle: {
                color: '#ddd'
            }
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: 'rgba(22,126,226,0.2)',
                type: 'dashed'
            }
        }
    },
    series: [{
        name: '生产时长',
        type: 'bar',
        barMaxWidth: 50,
        itemStyle: {
            color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                    {offset: 0, color: '#3387ec'},
                    {offset: 1, color: '#7BC9FF'}
                ]
            )
        },
        // data: [4.8, 6.4, 2.4, 10.6, 6.5, 4.6, 4.6]
    }]
};
var option_line1 = {//设备使用率折线图
    color: '#29d897',
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                type: 'dashed',
                color: '#aaa'
            }
        }
    },
    grid: {
        top: 15,
        left: 10,
        right: 10,
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        type: 'category',
        // data: increaseArr(7, 1),
        axisLine: {
            lineStyle: {
                color: '#ddd'
            }
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            lineStyle: {
                color: '#DDDDDD'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22,126,226,0.2)'],
                type: 'dashed'
            }
        }
    },
    series: [{
        name: '设备使用率',
        type: 'line',
        // data: randomFun(7, 0, 100, 1),
        showSymbol: false,
        symbolSize: 1,
        lineStyle: {
            width: 4,
            color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                    offset: 0, color: '#96ffd8' // 0% 处的颜色
                }, {
                    offset: 1, color: '#29d897' // 100% 处的颜色
                }]
            }
        },
    }]
};
var option_bar2 = {//今日用电量柱状图
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    grid: {
        top: 10,
        left: 15,
        right: 18,
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        type: 'category',
        // data: increaseArr2(24, 0),
        axisLine: {
            lineStyle: {
                color: '#ddd'
            }
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            lineStyle: {
                color: '#DDDDDD'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22,126,226,0.2)'],
                type: 'dashed'
            }
        }
    },
    series: [{
        name: '用电量',
        type: 'bar',
        // data: randomFun(24, 0, 199, 1),
        itemStyle: {
            normal: {
                //不同时段柱子设置不同颜色
                color: function (params) {
                    let colorList = [
                        "#009AEA",//谷 0-8
                        "#F2CB6B",//平 12-17，21-24
                        "#FF8B35"//峰 8-12，17-21
                    ];
                    if (Number(params.name.substr(0, 2)) >= 0 && Number(params.name.substr(0, 2)) < 8) {//谷
                        return colorList[0];
                    } else if ((Number(params.name.substr(0, 2)) >= 12 && Number(params.name.substr(0, 2)) < 17) || (Number(params.name.substr(0, 2)) >= 21)) {
                        return colorList[1];
                    } else {
                        return colorList[2]
                    }
                }
            }
        }
    }]
};
var option_radar = {//用电分析雷达图
    title: {
        text: '',
        bottom: 0,
        left: 'center',
        textStyle: {
            fontSize: 12,
            fontWeight: 400
        }
    },
    color: '#1890FF',
    tooltip: {},
    radar: {
        name: {
            textStyle: {
                color: '#666'
            }
        },
        center: ['50%', '45%'],
        radius: '70%',
        indicator: [
            {name: '电压偏差', max: 100},
            {name: '频率偏差', max: 100},
            {name: '三相不平衡', max: 100},
            {name: '负载率', max: 100},
            {name: '功率因数', max: 100}
        ],
        axisLine: {
            lineStyle: {
                color: '#ddd'
            }
        },
        splitLine: {
            lineStyle: {
                color: ['#e9e9e9']
            }
        },
        splitArea: {
            areaStyle: {
                color: ['rgba(250,250,250,0.1)', 'rgba(200,200,200,0.1)']
            }
        }
    },
    series: [{
        name: '用电分析',
        type: 'radar',
        showSymbol: false,
        areaStyle: {
            color: 'rgba(13, 98, 177, 0.3)'
        },
        lineStyle: {
            color: '#1890FF'
        },
        label: {
            show: true,
            formatter: '{c}'
        },
        data: [{
            value: [0, 0, 0, 0, 0]
        }]
    }]
};
var option_line2 = {//实时功率折线图
    color: '#5B8FF9',
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                type: 'dashed',
                color: '#aaa'
            }
        }
    },
    grid: {
        top: 15,
        left: 15,
        right: 18,
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        type: 'category',
        // data: increaseArr2(24, 0),
        axisLine: {
            lineStyle: {
                color: '#ddd'
            }
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            lineStyle: {
                color: '#DDDDDD'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22,126,226,0.2)'],
                type: 'dashed'
            }
        }
    },
    series: [{
        name: '功率',
        type: 'line',
        // data: randomFun(24, 0, 100, 1),
        showSymbol: false,
        symbolSize: 1
    }]
};
var option_pictorialBar1 = {//电价对比象形柱图
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            lineStyle: {
                color: 'transparent'
            }
        }
    },
    grid: {
        top: 30,
        bottom: 0,
        containLabel: true
    },
    xAxis: [{
        data: ['当前', '昨日', '上月'],
        axisTick: {show: false},
        axisLine: {show: false},
        axisLabel: {
            textStyle: {
                color: '#333',
                fontSize: 14,
                fontWeight: 'bold'
            }
        }
    }],
    yAxis: {
        splitLine: {show: false},
        axisTick: {show: false},
        axisLine: {show: false},
        axisLabel: {show: false}
    },
    animationEasing: 'elasticOut',
    series: [{
        type: 'pictorialBar',
        symbol: 'path://M495.8 8.4v1014.9L219.1 909M524.8 8.4v1014.9L801.5 909',
        label: {
            show: true,
            position: 'top',
            fontSize: 16
        },
        data: [{
            value: 0.638,
            itemStyle: {
                color: '#5B8FF9'
            }
        }, {
            value: 0.6928,
            itemStyle: {
                color: '#82D0EF'
            }
        }, {
            value: 0.6792,
            itemStyle: {
                color: '#F6BD16'
            }
        }]
    }]
};
var option_bar3 = {//用电分析柱状/折线图
    legend: {},
    color: ['#C6F694', '#8F74FF', '#FFB214', '#1362FF', '#FB7D1B', '#0096FF'],
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                type: 'dashed',
                color: '#aaa'
            }
        }
    },
    grid: {
        top: 45,
        left: 10,
        right: 10,
        bottom: 25,
        containLabel: true
    },
    xAxis: {
        type: 'category',
        // data: increaseArr2(24, 0),
        axisLine: {
            lineStyle: {
                color: '#ddd'
            }
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            lineStyle: {
                color: '#DDDDDD'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#666'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22,126,226,0.2)'],
                type: 'dashed'
            }
        }
    },
    dataZoom: [{
        type: 'slider',
        startValue: 17,
        endValue: 23,
        bottom: 0,
        top: 380
    }],
    series: [{
        name: '电压偏差',
        type: 'bar',
        // data: randomFun(24, 60, 100, 1),
        itemStyle: {
            barBorderRadius: [13, 13, 0, 0]
        }
    }, {
        name: '功率因数',
        type: 'bar',
        // data: randomFun(24, 60, 100, 1),
        itemStyle: {
            barBorderRadius: [13, 13, 0, 0]
        }
    }, {
        name: '频率偏差',
        type: 'bar',
        // data: randomFun(24, 60, 100, 1),
        itemStyle: {
            barBorderRadius: [13, 13, 0, 0]
        }
    }, {
        name: '三相不平衡',
        type: 'bar',
        // data: randomFun(24, 60, 100, 1),
        itemStyle: {
            barBorderRadius: [13, 13, 0, 0]
        }
    }, {
        name: '负载率',
        type: 'bar',
        // data: randomFun(24, 60, 100, 1),
        itemStyle: {
            barBorderRadius: [13, 13, 0, 0]
        }
    }, {
        name: '健康指数',
        type: 'line',
        // data: randomFun(24, 60, 100, 1),
        symbolSize: 4
    }]
};
